package krush.rezepte;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import strukturen.Helpers;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class Wizard extends Activity 
{
	private static final int SELECT_PICTURE = 1;
	private static final int TAKE_PICTURE = 2;
	
	private boolean imageSet = false;
	private String filename;
	private Bitmap foto;
		
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rezept_wizard);
        
      
        Log.e("krush2", "onCreate()");
        
      RadioGroup rg = (RadioGroup)findViewById(R.id.bild_radio_group);
      rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) 
		{
			LinearLayout mitBild = (LinearLayout)findViewById(R.id.mit_bild_layout);
			LinearLayout ohneBild = (LinearLayout)findViewById(R.id.ohne_bild_layout);
			
			if (checkedId == R.id.bild_radio_button)
			{
				mitBild.setVisibility(View.VISIBLE);
				ohneBild.setVisibility(View.GONE);
			}
			else
			{
				ohneBild.setVisibility(View.VISIBLE);
				mitBild.setVisibility(View.GONE);
			}
			
		}
	});
      DBHelper db = new DBHelper(this);
      
      Spinner sp = (Spinner)findViewById(R.id.kategorie_spinner);
      ArrayAdapter<String> mAd = new ArrayAdapter<String>(this, R.layout.spinner_entry, db.getKategorienAsStringArray());
      mAd.setDropDownViewResource(R.layout.spinner_entry);
      db.close();
      sp.setAdapter(mAd);
      
      //FOTO SETZEN UND EVTL. ROTIEREN
      if (foto == null)
      {
    	  Log.e("krush2", "leaving onCreate() -> foto=null");
    	  File file=getFileName();
    	  InputStream is;
		try {
			is = new FileInputStream(file);
			 Bitmap bmp = BitmapFactory.decodeStream(is);
		     Log.e("krush2", "SettingBitmap: " + bmp.getHeight());
		     
		     int tempW = bmp.getWidth();
		     int tempH = bmp.getHeight();

		     if (tempW>tempH) {
		         Matrix mtx = new Matrix();
		         mtx.postRotate(90);
		         Bitmap rotatedBitmap = Bitmap.createBitmap(bmp, 0,0,tempW, tempH, mtx, true);
		         FileOutputStream out = new FileOutputStream(getFileName());
		         rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
		         ((ImageView)findViewById(R.id.bild_bild)).setImageBitmap(rotatedBitmap);
		     }
		     else
		     {
		    	 ((ImageView)findViewById(R.id.bild_bild)).setImageBitmap(bmp);
		     }
		     imageSet = true;
		} catch (FileNotFoundException e) {
			Log.e("krush2", "FNFNFNFNFNFNFNFNFNFNFNFNFNFNF " + getFileName());
			e.printStackTrace();
		}
	       
    	  
      }
      else
    	  Log.e("krush2", "leaving onCreate() -> foto=" + foto.toString());
      
    }
	
	@Override
	public void onConfigurationChanged(Configuration c)
	{		
		super.onConfigurationChanged(c);
		Log.e("krush2", "onConfigurationChanged()");
		  if (foto != null)
	        	((ImageView)findViewById(R.id.bild_bild)).setImageBitmap(foto);
	}
	
	public void bildausgalerie(View v)
	{
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, SELECT_PICTURE); 
	}	
	
	public static File getFileName()
	{			
		Log.e("krush2", "getFilename()");
		 return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/krush.rezepte",  "image.tmp");		
        
	}
	
	
	public void bildvonkamera(View v)
	{
		Log.e("krush2", "Filename(bvk): " + getFileName());
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(getFileName()));
		intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_SENSOR);
		startActivityForResult(intent, TAKE_PICTURE);		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
	    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
	    Log.e("krush", "RESULT!!");
	    Toast.makeText(this, "result! ", Toast.LENGTH_LONG);
	    
	    switch(requestCode) { 
	    case SELECT_PICTURE:
	        if(resultCode == RESULT_OK)
	        {  
	            Uri selectedImage = imageReturnedIntent.getData();
	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();

	            try
	            {
	            	Helpers.copy(filePath, getFileName().getCanonicalPath());
	            }
	            catch(IOException e)
	            {
	            	Log.e("krush2", "from gallery " + e.toString());
	            }
	            
	            
	            if (foto == null)
	            {
	          	  Log.e("krush2", "from gallery -> foto=null");
	          	  File file=getFileName();
	          	  InputStream is;
	      		try {
	      			is = new FileInputStream(file);
	      			 Bitmap bmp = BitmapFactory.decodeStream(is);
	      		     Log.e("krush2", "SettingBitmap(fromGallery): " + bmp.getHeight());
	      		     
	      		     int tempW = bmp.getWidth();
	      		     int tempH = bmp.getHeight();

	      		     if (tempW>tempH) {
	      		         Matrix mtx = new Matrix();
	      		         mtx.postRotate(90);
	      		         Bitmap rotatedBitmap = Bitmap.createBitmap(bmp, 0,0,tempW, tempH, mtx, true);
	      		         FileOutputStream out = new FileOutputStream(getFileName());
	      		         rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
	      		         ((ImageView)findViewById(R.id.bild_bild)).setImageBitmap(rotatedBitmap);
	      		     }
	      		     else
	      		     {
	      		    	 ((ImageView)findViewById(R.id.bild_bild)).setImageBitmap(bmp);
	      		     }
	      		     imageSet = true;
	      		} catch (FileNotFoundException e) {
	      			Log.e("krush2", "FNFNFNFNFNFNFNFNFNFNFNFNFNFNF!!!!! " + getFileName());
	      			e.printStackTrace();
	      		}
	      	       
	          	  
	            }
	            else
	          	  Log.e("krush2", "leaving onCreate() -> foto=" + foto.toString());
	            
	            
	            
	            
	        }
	        else
	        {
	        	Toast.makeText(this, "FEHLER BEI FOTO", Toast.LENGTH_LONG);
	        }
	        break;
	    case TAKE_PICTURE:
	    	if(resultCode == RESULT_OK)
	    	{	    			
	    			//SOLL HIER WAS HIN?? JA LÖSCHEN AUS DER GALERIE!!
	    	}
	    	else
	        {
	        	Toast.makeText(this, "FEHLER BEI FOTO", Toast.LENGTH_LONG);
	        }
	    	break;
	    }
	}

	public void fertig(View v)
	{
		TextView rezName = (TextView)findViewById(R.id.rezept_name_edit_text);
		TextView verw = (TextView)findViewById(R.id.verweis_text_field);
		TextView such = (TextView)findViewById(R.id.suchbegriffe_edit_text);
		TextView bem = (TextView)findViewById(R.id.bemerkungen_edit_text);
		RadioButton verwRB = ((RadioButton)findViewById(R.id.kein_bild_radio_button));
		RadioButton bildRB = ((RadioButton)findViewById(R.id.bild_radio_button));
		Spinner spinner = ((Spinner)findViewById(R.id.kategorie_spinner));
	
		DBHelper db = new DBHelper(this);
		
		String fehlertext = "";
		int kat_id = -1;
		
		if (rezName.getText().length() == 0)		
			fehlertext += "Bitte Namen für Rezept eingeben\n";
		
		if (!imageSet && bildRB.isChecked())
			fehlertext += "Bitte Bild auswählen\n";
		
		if ( verwRB.isChecked() && verw.getText().length() == 0 )		
			fehlertext += "Bitte Verweis eingeben\n";
		
		if (spinner.getSelectedItemPosition() == 0)
			fehlertext += "Bitte Kategorie auswählen\n";
		else
			kat_id = db.getKategorien().get(spinner.getSelectedItemPosition() - 1).getId();
		 
		
		if (such.getText().length() == 0)		
			fehlertext += "Bitte Suchbegriffe eingeben\n";
		
		
		if (fehlertext.equals(""))
		{
			boolean copyErfolg = true;
			if (imageSet && bildRB.isChecked())
			{
				File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/krush.rezepte",  "im" + String.valueOf(System.currentTimeMillis()) + ".jpg");
				
				try {
					Helpers.copy(getFileName().getCanonicalPath(), f.getCanonicalPath());
					filename = f.getCanonicalPath();
					Log.e("krush2", "Filename auf " + filename + " gesetzt!");
				}
				catch (IOException e) 
				{
					Log.e("krush2", e.toString());
					copyErfolg = false;
				}
			}
				
			if (copyErfolg)
			{	
				
				if (verwRB.isChecked())
					filename = verw.getText().toString();
				
				long pnr = db.insertRez(rezName.getText().toString(), kat_id, filename, bem.getText().toString());
	
				db.insertSuchbegriffe(such.getText().toString(), pnr);
							
				Toast.makeText(this, "Rezept \"" + rezName.getText() + "\" eingetragen!\n" + filename, Toast.LENGTH_LONG).show();
				this.finish();
			}
			else
			{
				Toast.makeText(this, "Kopier-Fehler", Toast.LENGTH_LONG).show();
			}
					
		}
		else
		{
			
			Toast.makeText(this, fehlertext, Toast.LENGTH_LONG).show();
		}
		db.close();
		
	}
	
	public static File convertImageUriToFile (Uri imageUri, Activity activity)  {
		Cursor cursor = null;
		try {
		    String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
		    cursor = activity.managedQuery( imageUri,
		            proj, // Which columns to return
		            null,       // WHERE clause; which rows to return (all rows)
		            null,       // WHERE clause selection arguments (none)
		            null); // Order-by clause (ascending by name)
		    int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		    int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
		    if (cursor.moveToFirst()) {
		        String orientation =  cursor.getString(orientation_ColumnIndex);
		        return new File(cursor.getString(file_ColumnIndex));
		    }
		    return null;
		} finally {
		    if (cursor != null) {
		        cursor.close();
		    }
		}
		}
	
}
